package com.ebanma.cloud.usertestall.interceptor;

import com.ebanma.cloud.usertestall.domain.common.ErrorCode;
import com.ebanma.cloud.usertestall.exception.BusinessException;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: <a href="liuhe41@faw.com.cn">刘赫</a>
 * @date: 2023/3/24
 * @time: 17:30
 * @description:
 */
@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RateLimitInterceptor.class);

    /**
     * 速度限制器(QPS为1，为了方便测试，正常为10或100)
     */
    private static final RateLimiter rateLimiter = RateLimiter.create(1);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!rateLimiter.tryAcquire()) {
            logger.error("系统已经被限流了！！");

            throw new BusinessException(ErrorCode.RATE_LIMIT_ERROR);
        }

        return true;
    }
}
